import 'dart:async';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:magic_car/common/global.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:magic_car/util/colors.dart';
import 'package:magic_car/util/config.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:toast/toast.dart';
import 'package:magic_car/main.dart';
import 'dart:io';

class ForgetPassPage extends StatefulWidget {
  //LoginPage({Key key, this.title,this.role}) : super(key: key);

  //final String title;
  final String role;

  ForgetPassPage(this.role);

  @override
  _MyHomePageState createState() => new _MyHomePageState(this.role);
}

class _MyHomePageState extends State<ForgetPassPage> {
  bool _phoneState, _pwdState, codeState = false;
  String _checkStr;
  String roles;
  _MyHomePageState(this.roles);

  TextEditingController _phonecontroller = new TextEditingController();
  TextEditingController _pwdcontroller = new TextEditingController();
  TextEditingController _codecontroller = new TextEditingController();

  Timer _timer;
  int _seconds = 60;
  String _verifyStr = '获取验证码';
  void _checkPhone() {
    if (_phonecontroller.text.isNotEmpty &&
        _phonecontroller.text.trim().length == 11) {
      _phoneState = true;
    } else {
      _phoneState = false;
    }
  }

  void _checkPwd() {
    if (_pwdcontroller.text.isNotEmpty &&
        _pwdcontroller.text.trim().length >= 6) {
      _pwdState = true;
    } else {
      _pwdState = false;
    }
  }

  void _checkCode() {
    if (_codecontroller.text.isNotEmpty) {
      codeState = true;
    } else {
      codeState = false;
    }
  }

  @override
  void initState() {
    // TODO: implement initState

    super.initState();
  }

  /// 启动倒计时的计时器。
  void _startTimer() {
    print('开始计时');
    // 计时器（`Timer`）组件的定期（`periodic`）构造函数，创建一个新的重复计时器。
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      print(_seconds.toString());
      if (_seconds == 0) {
        _cancelTimer();

        setState(() {
          _verifyStr = '重新发送';
          _seconds = 60;
        });
        return;
      }

      _verifyStr = '已发送$_seconds' + 's';
      setState(() {
        _verifyStr = '已发送$_seconds' + 's';
      });
      _seconds--;
      if (_seconds == 0) {
        _verifyStr = '重新发送';
      }
    });
  }

  /// 取消倒计时的计时器。
  void _cancelTimer() {
    // 计时器（`Timer`）组件的取消（`cancel`）方法，取消计时器。
    _timer?.cancel();
  }

  //发送验证码
  sendcode() {
    FocusScope.of(context).requestFocus(FocusNode());
    print('获取验证码');
    if (_phonecontroller.text.trim().length == 0) {
      Toast.show("填写手机号", context);
      return;
    }
    Map<String, String> map = new Map();
    map["mobile"] = _phonecontroller.text.trim();
    HttpHelper.post(HttpHelper.API_SendCode, (data) {
      if (data != null) {
        print(data);
        Toast.show(data["msg"], context);

        if (data["code"].toString() == "1") {
          // Navigator.pop(context);
          _startTimer();
          setState(() {
            // orderInfo=data["data"];
          });
        }
      }
    }, params: map);
  }

  submit() async {
    FocusScope.of(context).requestFocus(FocusNode());
    Map<String, String> map = new Map();
    // if(_phonecontroller.text==""||_pwdcontroller.text==""||_codecontroller.text=="")return;
    map["mobile"] = _phonecontroller.text.trim();
    map["password"] = _pwdcontroller.text.trim();
    map["code"] = _codecontroller.text.trim();

    //isbussiness
    SharedPreferences pref = await SharedPreferences.getInstance();
    if (pref.getString('role') == "0") {
      //车商
      map["isbussiness"] = "1";
    }
    HttpHelper.post(HttpHelper.API_ResetPass, (data) async {
      if (data != null) {
        print(data);
        Toast.show(data["msg"], context);

        if (data["code"].toString() == "1") {
          Navigator.pop(context);
        }
      }
    }, params: map);
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      backgroundColor: Colors.white,
      appBar: new AppBar(
        title: new Text('找回密码',style: TextStyle(fontSize: Config.title_size),),
        backgroundColor: Colors.white,
        elevation: 0,
        // backgroundColor: Color.fromRGBO(255, 204, 48, 1),
      ),
      body: new ListView(
        children: <Widget>[
          new Column(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              new Padding(
                  padding: new EdgeInsets.all(30.0),
                  child: new Image.asset(
                    'resource/images/user/user1.png',
                    scale: 1.2,
                  )),
              new Padding(
                  padding: new EdgeInsets.fromLTRB(20.0, 0.0, 20.0, 15.0),
                  child: new Container(
                      decoration: new BoxDecoration(
//背景
                        color: Colors.white,
                        //设置四周圆角 角度 这里的角度应该为 父Container height 的一半
                        borderRadius: BorderRadius.all(Radius.circular(5.0)),
                        //设置四周边框
                        border: new Border.all(
                            width: 1, color: Colours.border_papular_gray),
                      ),
                      child: new Column(children: <Widget>[
                        new Padding(
                            padding:
                                new EdgeInsets.fromLTRB(20.0, 0.0, 20.0, 0.0),
                            child: new Container(
                              height: 52,
                              child: new Stack(
                                alignment: new Alignment(1.0, 1.0),
                                //statck
                                children: <Widget>[
                                  new Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceEvenly,
                                      children: [
                                        new Padding(
                                          padding: new EdgeInsets.fromLTRB(
                                              0.0, 0.0, 15.0, 0.0),
                                          child: new Image.asset(
                                            'resource/images/user/user2.png',
                                            width: 20.0,
                                            height: 20.0,
                                            fit: BoxFit.fill,
                                          ),
                                        ),
                                        new Expanded(
                                          child: new TextField(
                                            controller: _phonecontroller,
                                            keyboardType: TextInputType.number,
                                            decoration: new InputDecoration(
                                              border: InputBorder.none,
                                              hintText: '请输入手机号',
                                              hintStyle: TextStyle(fontSize: 16),
                                            ),
                                          ),
                                        ),
                                      ]),
                                  new IconButton(
                                    icon: new Icon(Icons.clear,
                                        color:
                                            Color.fromRGBO(235, 235, 235, 1)),
                                    onPressed: () {
                                      _phonecontroller.clear();
                                    },
                                  ),
                                ],
                              ),
                            )),
                        new Padding(
                          padding: new EdgeInsets.fromLTRB(0.0, 1.0, 0.0, 0.0),
                          child: Container(
                            height: 1,
                            color:Colours.border_papular_gray,
                          ),
                        ),
                        new Padding(
                            padding:
                                new EdgeInsets.fromLTRB(20.0, 0.0, 20.0, 0.0),
                            child: new Container(
                                height: 52,
                                child: new Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceEvenly,
                                    children: [
                                      new Padding(
                                        padding: new EdgeInsets.fromLTRB(
                                            0.0, 0.0, 15.0, 0.0),
                                        child: new Image.asset(
                                          'resource/images/user/user3.png',
                                          width: 20.0,
                                          height: 20.0,
                                          fit: BoxFit.fill,
                                        ),
                                      ),
                                      new Expanded(
                                        flex: 1,
                                        child: new TextField(
                                          controller: _codecontroller,
                                          decoration: new InputDecoration(
                                            border: InputBorder.none,
                                            hintText: '输入验证码',
                                            hintStyle: TextStyle(fontSize: 16),
                                            suffixIcon: new IconButton(
                                              icon: new Icon(Icons.clear,
                                                  color:Colours.border_papular_gray),
                                              onPressed: () {
                                                _codecontroller.clear();
                                              },
                                            ),
                                          ),
                                        ),
                                      ),
                                      Expanded(
                                        child: new Padding(
                                          padding: new EdgeInsets.fromLTRB(
                                              10, 0, 10, 0),
                                          child: Align(
                                              alignment: Alignment.centerRight,
                                              child: new Container(
                                                child: new Material(
                                                  //INK可以实现装饰容器
                                                  child: new Ink(
                                                    //用ink圆角矩形
                                                    // color: Colors.red,
                                                    decoration:
                                                        new BoxDecoration(
                                                      //背景
                                                      color: Colors.white,
                                                      //设置四周圆角 角度
                                                      borderRadius:
                                                          BorderRadius.all(
                                                              Radius.circular(
                                                                  5.0)),
                                                      //设��四周边框
                                                      border: new Border.all(
                                                          width: 1,
                                                          color: Colours.app_main),
                                                    ),
                                                    child: new InkWell(
                                                        //圆角设置,给水波纹也设置同样的圆角
                                                        //如果这里不设置就会出现矩形的水波纹效果
                                                        borderRadius:
                                                            new BorderRadius
                                                                .circular(15.0),
                                                        //设置点击事件回调
                                                        onTap: () {
                                                          if (_seconds == 60) {
                                                            sendcode();
                                                          }
                                                        },
                                                        child: Container(
                                                          //设置 child 居中
                                                          alignment:
                                                              Alignment(0, 0),
                                                          height: 35,
                                                          width: 105,
                                                          child: Text(
                                                            _verifyStr,
                                                            style: TextStyle(
                                                                color: Colours.app_main),
                                                          ),
                                                        )),
                                                  ),
                                                ),
                                              )
                                              // child: new RaisedButton(
                                              //   child: Text('申请补考'),
                                              //   onPressed: () {},
                                              // ),
                                              ),
                                          // child: new RaisedButton(
                                          //   onPressed: () {
                                          //     sendcode();
                                          //   },
                                          //   child: Text('获取验证码'),
                                          // ),
                                        ),
                                        flex: 1,
                                      ),
                                    ]))),
                        new Padding(
                          padding: new EdgeInsets.fromLTRB(0.0, 1.0, 0.0, 0.0),
                          child: Container(
                            height: 1,
                            color: Colours.border_papular_gray,
                          ),
                        ),
                        new Padding(
                            padding:
                                new EdgeInsets.fromLTRB(20.0, 0.0, 20.0, 0.0),
                            child: new Container(
                              height: 52,
                              child: new Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceEvenly,
                                  children: [
                                    new Padding(
                                      padding: new EdgeInsets.fromLTRB(
                                          0.0, 0.0, 15.0, 0.0),
                                      child: new Image.asset(
                                        'resource/images/user/user3.png',
                                        width: 20.0,
                                        height: 20.0,
                                        fit: BoxFit.fill,
                                      ),
                                    ),
                                    new Expanded(
                                      child: new TextField(
                                        controller: _pwdcontroller,
                                        decoration: new InputDecoration(
                                          border: InputBorder.none,
                                          hintText: '请输入密码',
                                          hintStyle: TextStyle(fontSize: 16),
                                          suffixIcon: new IconButton(
                                            icon: new Icon(Icons.clear,
                                                color: Color.fromRGBO(
                                                    235, 235, 235, 1)),
                                            onPressed: () {
                                              _pwdcontroller.clear();
                                            },
                                          ),
                                        ),
                                        obscureText: true,
                                      ),
                                    ),
                                  ]),
                            )),
                        // new Padding(
                        //   padding:
                        //       new EdgeInsets.fromLTRB(20.0, 1.0, 20.0, 40.0),
                        //   child: Container(
                        //     height: 1,
                        //     color: Color.fromRGBO(225, 225, 225, 1),
                        //   ),
                        // )
                      ]))),
              Padding(
                  padding: new EdgeInsets.fromLTRB(15.0, 0.0, 15.0, 0.0),
                  child:        
              new Container(
                width: double.infinity,
                // width: 340.0,
                child: new Card(
                  color: Colours.app_main,
                  elevation: 0,
                  child: new FlatButton(
                    child: new Padding(
                      padding: new EdgeInsets.all(10.0),
                      child: new Text(
                        '提交',
                        style:
                            new TextStyle(color: Colors.white, fontSize: 16.0),
                      ),
                    ),
                    onPressed: () {
                      _checkPhone();
                      _checkPwd();
                      _checkCode();
                      if (_phoneState && _pwdState && codeState) {
                        _checkStr = '正在提交！';
                        submit();
                      } else {
                        if (!_phoneState) {
                          _checkStr = '请输入11位手机号！';
                        } else if (!_pwdState) {
                          _checkStr = '请输入6-10位密码！';
                        } else if (!codeState)
                          _checkStr = '请输入验证码！';
                        else
                          _checkStr = '正在验证';
                      }

                      // print(_checkStr);
                      Toast.show(_checkStr, context);
                    },
                  ),
                ),
              )),
            ],
          ),
        ],
      ),
    );
  }
}
